package com.course02.order_backend.controller.Ost;

import com.course02.order_backend.common.Ost.Result;
import com.course02.order_backend.dto.Ost.UserDTO;
import com.course02.order_backend.service.Ost.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public Result register(@Valid @RequestBody UserDTO userDTO) {
        try {
            // 1. 打印接收的用户信息（方便核对参数是否正确）
            logger.info("收到注册请求，用户信息：{}", userDTO);

            // 2. 调用服务层执行注册
            int rows = userService.register(userDTO);

            // 3. 根据影响行数返回结果
            if (rows > 0) {
                logger.info("用户注册成功，用户名：{}", userDTO.getUsername());
                return Result.success("注册成功");
            } else {
                logger.warn("用户注册失败，影响行数为0，用户名：{}", userDTO.getUsername());
                return Result.error("注册失败，请稍后重试");
            }
        } catch (Exception e) {
            // 4. 捕获所有异常，避免响应丢失（关键修复点）
            logger.error("注册过程发生异常，用户信息：{}，异常信息：{}", userDTO, e.getMessage(), e);
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }
}